// unit-detail.js - 单词单元详情页面逻辑

Page({
  data: {
    // 单元信息
    unitId: '',
    unitName: '日常英语单词',
    totalWordsCount: 20,
    learnedWordsCount: 12,
    newWordsCount: 8,
    progressPercentage: 60,
    masteryLevel: 75,
    totalStudyTime: 45,
    nextReviewTime: '明天',
    
    // 单词过滤条件
    wordFilter: 'all',
    
    // 单词列表
    words: [
      {
        id: '1',
        word: 'apple',
        phonetic: '/ˈæpl/',
        meaning: '苹果',
        example: 'I eat an apple every day.',
        isLearned: true
      },
      {
        id: '2',
        word: 'banana',
        phonetic: '/bəˈnɑːnə/',
        meaning: '香蕉',
        example: 'Bananas are yellow.',
        isLearned: true
      },
      {
        id: '3',
        word: 'cat',
        phonetic: '/kæt/',
        meaning: '猫',
        example: 'The cat is sleeping.',
        isLearned: true
      },
      {
        id: '4',
        word: 'dog',
        phonetic: '/dɒɡ/',
        meaning: '狗',
        example: 'The dog is running.',
        isLearned: true
      },
      {
        id: '5',
        word: 'egg',
        phonetic: '/eɡ/',
        meaning: '鸡蛋',
        example: 'I eat an egg for breakfast.',
        isLearned: true
      },
      {
        id: '6',
        word: 'fish',
        phonetic: '/fɪʃ/',
        meaning: '鱼',
        example: 'Fish live in water.',
        isLearned: true
      },
      {
        id: '7',
        word: 'goat',
        phonetic: '/ɡəʊt/',
        meaning: '山羊',
        example: 'The goat is eating grass.',
        isLearned: true
      },
      {
        id: '8',
        word: 'hat',
        phonetic: '/hæt/',
        meaning: '帽子',
        example: 'I wear a hat in summer.',
        isLearned: true
      },
      {
        id: '9',
        word: 'ice',
        phonetic: '/aɪs/',
        meaning: '冰',
        example: 'The ice is cold.',
        isLearned: true
      },
      {
        id: '10',
        word: 'juice',
        phonetic: '/dʒuːs/',
        meaning: '果汁',
        example: 'I drink juice every morning.',
        isLearned: true
      },
      {
        id: '11',
        word: 'kite',
        phonetic: '/kaɪt/',
        meaning: '风筝',
        example: 'I fly a kite in the park.',
        isLearned: true
      },
      {
        id: '12',
        word: 'lion',
        phonetic: '/ˈlaɪən/',
        meaning: '狮子',
        example: 'The lion is the king of the jungle.',
        isLearned: true
      },
      {
        id: '13',
        word: 'milk',
        phonetic: '/mɪlk/',
        meaning: '牛奶',
        example: 'I drink milk every day.',
        isLearned: false
      },
      {
        id: '14',
        word: 'nose',
        phonetic: '/nəʊz/',
        meaning: '鼻子',
        example: 'I have a small nose.',
        isLearned: false
      },
      {
        id: '15',
        word: 'orange',
        phonetic: '/ˈɒrɪndʒ/',
        meaning: '橙子',
        example: 'I like orange juice.',
        isLearned: false
      },
      {
        id: '16',
        word: 'pen',
        phonetic: '/pen/',
        meaning: '钢笔',
        example: 'I write with a pen.',
        isLearned: false
      },
      {
        id: '17',
        word: 'queen',
        phonetic: '/kwiːn/',
        meaning: '女王',
        example: 'The queen lives in a palace.',
        isLearned: false
      },
      {
        id: '18',
        word: 'rabbit',
        phonetic: '/ˈræbɪt/',
        meaning: '兔子',
        example: 'The rabbit is eating carrots.',
        isLearned: false
      },
      {
        id: '19',
        word: 'sun',
        phonetic: '/sʌn/',
        meaning: '太阳',
        example: 'The sun is shining.',
        isLearned: false
      },
      {
        id: '20',
        word: 'tiger',
        phonetic: '/ˈtaɪɡə(r)/',
        meaning: '老虎',
        example: 'The tiger is very strong.',
        isLearned: false
      }
    ],
    
    // 显示的单词列表
    displayedWords: [],
    
    // 单词详情弹窗
    showWordDetailModal: false,
    selectedWord: null
  },

  onLoad: function(options) {
    // 从页面参数获取单元ID
    if (options && options.id) {
      this.setData({
        unitId: options.id
      });
    }
    
    // 加载单元数据
    this.loadUnitData();
  },

  onShow: function() {
    // 每次显示页面时刷新数据
    this.loadUnitData();
  },

  // 加载单元数据
  loadUnitData: function() {
    // 在实际应用中，这里会根据unitId从服务器获取单元数据
    // 目前使用本地模拟数据
    
    // 更新显示的单词列表
    this.updateDisplayedWords();
  },

  // 返回上一页
  navigateBack: function() {
    wx.navigateBack();
  },

  // 切换单词过滤条件
  switchWordFilter: function(e) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({
      wordFilter: filter
    });
    
    // 更新显示的单词列表
    this.updateDisplayedWords();
  },

  // 更新显示的单词列表
  updateDisplayedWords: function() {
    let filteredWords = this.data.words;
    
    // 根据过滤条件过滤单词
    if (this.data.wordFilter === 'learned') {
      filteredWords = this.data.words.filter(word => word.isLearned);
    } else if (this.data.wordFilter === 'unlearned') {
      filteredWords = this.data.words.filter(word => !word.isLearned);
    }
    
    this.setData({
      displayedWords: filteredWords
    });
  },

  // 显示单词详情
  showWordDetail: function(e) {
    const wordId = e.currentTarget.dataset.id;
    const selectedWord = this.data.words.find(word => word.id === wordId);
    
    this.setData({
      selectedWord,
      showWordDetailModal: true
    });
  },

  // 关闭单词详情弹窗
  closeWordDetailModal: function() {
    this.setData({
      showWordDetailModal: false,
      selectedWord: null
    });
  },

  // 播放单词发音
  playPronunciation: function() {
    // 在实际应用中，这里会调用语音API播放单词发音
    wx.showToast({
      title: '播放发音',
      icon: 'none'
    });
  },

  // 标记单词为已学
  markAsLearned: function() {
    if (!this.data.selectedWord) return;
    
    // 更新单词状态
    const updatedWords = this.data.words.map(word => {
      if (word.id === this.data.selectedWord.id) {
        return { ...word, isLearned: true };
      }
      return word;
    });
    
    // 更新统计数据
    const learnedWordsCount = updatedWords.filter(word => word.isLearned).length;
    const newWordsCount = updatedWords.filter(word => !word.isLearned).length;
    const progressPercentage = Math.round((learnedWordsCount / updatedWords.length) * 100);
    
    this.setData({
      words: updatedWords,
      learnedWordsCount,
      newWordsCount,
      progressPercentage
    });
    
    // 更新显示的单词列表
    this.updateDisplayedWords();
    
    // 关闭弹窗
    this.closeWordDetailModal();
    
    wx.showToast({
      title: '已标记为已学',
      icon: 'success'
    });
  },

  // 开始学习
  startLearning: function() {
    const app = getApp();
    const wordDataManager = app.globalData.wordDataManager;
    
    try {
      // 获取所有词书
      const allBooks = wordDataManager.getAllBooks();
      
      // 将所有词书的active状态设置为0（非激活）
      allBooks.forEach(book => {
        book.active = 0;
      });
      
      // 将当前词书的active状态设置为1（激活）
      const currentBook = allBooks.find(book => book.id === this.data.unitId);
      if (currentBook) {
        currentBook.active = 1;
        
        // 保存更新后的词书数据
        wordDataManager._saveBooks(allBooks);
        
        console.log('已设置词书为激活状态:', currentBook.name);
      }
    } catch (error) {
      console.error('设置词书激活状态失败:', error);
    }
    
    wx.navigateTo({
      url: '/pages/vocabulary/learning/learning?unitId=' + this.data.unitId
    });
  },

  // 开始测试
  startTest: function() {
    wx.navigateTo({
      url: '/pages/vocabulary/test/test?unitId=' + this.data.unitId
    });
  }
});